<?php

namespace App\Http\Controllers;

use App\Model\Files;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;

class FileController extends Controller
{

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {

    }


    public function rendering($hash)
    {
        $result = Files::where('hash', $hash)->first();
        if (!$result) {
            return $this->error('图片不存在', 404);
        }
//        return $this->success(['url' => $result->set_uri]);
        try {
            $s3 = app('aws')->createClient('s3');
            $result = $s3->getObject([
                'Bucket' => $result->s3_bucket,
                'Key' => $result->s3_key,
            ]);

            header("Content-Type: {$result['ContentType']}");
            echo $result['Body'];
//            return $this->success(['url'=>$result["@metadata"]["effectiveUri"]]);
        } catch (\Exception $e) {
            return $this->error('图片失败', 404);
        }
    }


    public function batch(Request $request)
    {
        $hashs = $request->input('hash', '');
        if (!$hashs) {
            return $this->error('参数不正确', 500);
        }
        $hashArr = explode(',', $hashs);
        $files = Files::whereIn('hash', $hashArr)->select('set_uri', 'hash', 'file_name as name')->get()->toArray();
        return $this->success($files);
    }

    //后期需验证前端域名限制
    public function puting(Request $request)
    {
//        dd($request->all());
        if (!env('APP_DEBUG', false)) {
            $domain = env('ALLOW_DOMAIN');
            $domain_list = explode(',', $domain);
            $host_url = $_SERVER['HTTP_HOST'];
            if (!in_array($host_url, $domain_list)) {
                return $this->error('无权访问', 500);
            }
        }
        $is_upload = $request->hasFile('photo');
        //   dd($is_upload);
        if ($is_upload) {
            try {
                $file = $request->file('photo');
                $file_path = $file->path();
                $file_name = $file->getClientOriginalName();
                $ext = $file->getMimeType();
                $size = $file->getSize();
                $max_size = env('MAX_SIZE');
                if ($size > $max_size) {
                    throw  new \Exception('图片尺寸过大，最大尺寸限制位：1M');
                }
                $e = substr($file_name, strpos($file_name, '.'));
                $md5 = md5_file($file_path);
                $result = Files::where('hash', $md5)->first();
                if ($result) {
                    return $this->success(['url' => route('getFile', ['hash' => $md5]), 'name' => $result->file_name, 'set_uri' => $result->set_uri, 'hash' => $md5, 'frontend' => $request->input('frontend', [])]);
                }
                $key = 'umijoy-' . $md5 . $e;


//                $s3 = app('aws')->createClient('s3');
//                $d = $s3->putObject(array(
//                    'Bucket' => 'umijoy',
//                    'Key' => $key,
//                    'SourceFile' => $file_path,
//
//                ));
                //2021-2-24更换为本地保存
//                if ($d && $d['ObjectURL']) {
//                    $m = new Files();
//                    $fileData = [
//                        'hash' => $md5,
//                        's3_bucket' => 'umijoy',
//                        's3_key' => $key,
//                        'file_name' => $file_name,
//                        'mime_type' => $ext,
//                        'size' => $size,
//                        'set_uri' => $d['ObjectURL']
//                    ];
//                    $m->setRawAttributes($fileData);
//                    if ($m->save($fileData)) {
//                        return $this->success([
//                            'url' => route('getFile', ['hash' => $md5]),
//                            'name' => $file_name, 'set_uri' => $d['ObjectURL'],
//                            'hash' => $md5,
//                            'frontend' => $request->input('frontend', [])
//                        ]);
//                    }
//                }
                //2021-2-24更换为本地保存
                //组装路径
                $path = 'img/';
                $showPath = $path;
                $path = realpath('./').'/'.$path;
                $filename=date('YmdHis').rand(0,1000).'.'.$file->guessClientExtension();
                $bool = $file->move($path, $filename);
                $url = url($showPath.$filename);
                if ($bool) {
                    $m = new Files();
                    $fileData = [
                        'hash' => $md5,
                        's3_bucket' => 'umijoy',
                        's3_key' => $key,
                        'file_name' => $file_name,
                        'mime_type' => $ext,
                        'size' => $size,
                        'set_uri' =>$url
                    ];
                    $m->setRawAttributes($fileData);
                    if ($m->save($fileData)) {
                        return $this->success([
                            'url' => route('getFile', ['hash' => $md5]),
                            'name' => $file_name,
                            'set_uri' =>$url,
                            'hash' => $md5,
                            'frontend' => $request->input('frontend', [])
                        ]);
                    }
                }
            } catch (\Exception $e) {
                return $this->error($e->getMessage(), 403);
            }
        }
        return $this->error('上传失败', 500);
    }
}
